package com.hn.utils.http;

import com.hn.Entry.MapEntry;
import com.hn.Entry.ServerEntry;
import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.*;

public class CatApiUtil {
    private static final String url="http://inadvertently.top/steamApi/?";
    private static final String mapUrl="https://www.bluearchive.top/api/blog/map/list?pageNum=1&pageSize=99999";
    //获取服务器信息
    public static List<ServerEntry> getMessage(Map<String, String> paths) {
        StringBuilder questPath= new StringBuilder();
        questPath.append(url);
        paths.forEach((key, value) -> {
            questPath.append("paths=").append(value).append("&");
        });
        return sendHttpRequest(questPath.toString());
    }

    //获取所有服务器数据
    private static List<ServerEntry> sendHttpRequest(String url) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            // 保存结果的List
            List<ServerEntry> resultList = new ArrayList<>();

            // 假设服务器返回的是JSON格式的字符串
            String jsonString = response.body().string();

            // 使用JSONArray来解析JSON数组
            JSONArray jsonArray = new JSONArray(jsonString);
            //获取全部地图
            Map<String, MapEntry> mapList = getMap();
            // 遍历JSON数组中的每个元素（每个元素都是一个JSONObject）
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                if (jsonObject.has("response")) {
                    JSONObject responseObj = jsonObject.getJSONObject("response");
                    if (responseObj.has("servers")) {
                        JSONArray serversArray = responseObj.getJSONArray("servers");
                        // 遍历服务器列表
                        for (int j = 0; j < serversArray.length(); j++) {
                            JSONObject serverObj = serversArray.getJSONObject(j);
                            // 提取服务器的信息，例如名字和地址
                            String name = serverObj.getString("name");
                            String addr = serverObj.getString("addr");
                            Integer appid = serverObj.getInt("appid");
                            Integer players = serverObj.getInt("players");
                            Integer max_players = serverObj.getInt("max_players");
                            String product = serverObj.getString("product");
                            String version = serverObj.getString("version");
                            String map = serverObj.getString("map");
                            MapEntry mapEntry = mapList.get(map.trim());
                            if (mapEntry == null){
                                mapEntry = new MapEntry();
                                mapEntry.setLabel("暂无译名");
                            }
                            ServerEntry serverEntryDao = ServerEntry.builder()
                                    .setName(name)
                                    .setAddr(addr)
                                    .setAppid(appid)
                                    .setPlayers(players)
                                    .setMax_players(max_players)
                                    .setProduct(product)
                                    .setVersion(version)
                                    .setMap(map)
                                    .setMapName(mapEntry.getLabel())
                                    .setMapImg(mapEntry.getMapUrl())
                                    .build();
                            resultList.add(serverEntryDao);
                        }
                    }
                }
            }
            return resultList;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //获取所有地图数据
    public static Map<String, MapEntry> getMap() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(mapUrl)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            HashMap<String, MapEntry> mapMap = new HashMap<>();
            // 假设服务器返回的是JSON格式的字符串
            String jsonString = response.body().string();
            // 将字符串转换为JSONObject
            JSONObject jsonObject = new JSONObject(jsonString);
            // 获取rows数组
            JSONArray rowsArray = jsonObject.getJSONArray("rows");
            // 遍历rows数组
            for (int i = 0; i < rowsArray.length(); i++) {
                JSONObject row = rowsArray.getJSONObject(i);
                MapEntry mapEntry = new MapEntry();
                mapEntry.setLabel(row.optString("label"));
                mapEntry.setMapUrl(row.optString("mapUrl"));
                mapMap.put(row.getString("name").trim(), mapEntry);
            }
            return mapMap;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
